import os, json, logging.handlers
from bs4 import BeautifulSoup
from config import DIR_PATH
import pymysql

# 断言工具封装
def common_assert(response, status_code=None, expect_json=None, expect_text=None):
    # 如果status_code不为空，那么就断言
    if status_code:
        assert response.status_code == status_code, "预期状态码：{} != 实际状态码：{}".format(status_code, response.status_code)
    if expect_json:
        assert expect_json in response.json().get("description"), " 实际结果：{} 不包含 预期结果：{} ".format(
            response.json().get("description"), expect_json)
    if expect_text:
        assert expect_text in response.text, "实际结果：{} 不包含 预期结果：{}".format(response.text, expect_text)


# 读取json工具
def read_json(filename, key):
    filepath = DIR_PATH + os.sep + "data" + os.sep + filename
    arrs = []
    with open(filepath, "r", encoding="utf-8")as f:
        for data in json.load(f).get(key):
            arrs.append(tuple(data.values())[1:])
    return arrs


# 日志工具
class GetLog:
    log = None

    @classmethod
    def get_log(cls):
        if cls.log is None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置入口级别
            cls.log.setLevel(logging.INFO)
            # 设置文件
            filepath = DIR_PATH + os.sep + "log" + os.sep + "p2p.log"

            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")
            # 设置格式
            fm = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fmt = logging.Formatter(fm)
            # 将格式器添加到文件中
            tf.setFormatter(fmt)
            # 将文件添加到日志器中
            cls.log.addHandler(tf)
        return cls.log


# 提取html
def html_parser(result):
    # 1、提取html
    html = result.json().get("description").get("form")
    # 2、获取bs对象
    bs = BeautifulSoup(html, "html.parser")
    # 3、提取url
    url = bs.form.get("action")
    print("提取的三方url为：", url)
    data = {}
    # 4、提取所有input数据
    for input in bs.find_all("input"):
        data[input.get("name")] = input.get("value")
    return url, data


# 连接数据库工具
def connect_mysql(sql):
    conn = None
    cursor = None
    try:
        # 获取连接对象
        conn = pymysql.connect(host="121.43.169.97",
                               user="student",
                               password="P2P_student_2022",
                               database="czbk_member",
                               port=3306,
                               charset="utf8",
                               autocommit=True)
        # 获取游标对象
        cursor = conn.cursor()
        # 执行sql语句
        cursor.execute(sql)
        # 返回什么结果
        if sql.lower().split()[0] == "select":
            # 查询返回所有数据
            return cursor.fetchall()
        else:
            # 非查询返回受影响的行数
            return cursor.rowcount
    except Exception as e:
        print("出错了：",e)
        # 回滚
        conn.rollback()
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()

# 清除数据
def clear_data():
    sql_1 = """
        delete info.* from mb_member as mb inner join mb_member_info  as info on info.member_id = mb.id where mb.phone in ("13600001111","13600001112","13600001113","13600001114");
    """
    connect_mysql(sql_1)
    sql_2 = """
        delete login.* from mb_member as mb inner join mb_member_login_log  as login on login.member_id = mb.id where mb.phone in ("13600001111","13600001112","13600001113","13600001114");
        """
    connect_mysql(sql_2)
    sql_3 = """
        delete from mb_member where phone in ("13600001111","13600001112","13600001113","13600001114");
        """
    connect_mysql(sql_3)
    sql_4 = """
        delete from mb_member_register_log where phone in ("13600001111","13600001112","13600001113","13600001114");
        """
    connect_mysql(sql_4)

if __name__ == '__main__':
    sql_1 = "select * from mb_member as mb inner join mb_member_info  as info on info.member_id = mb.id where mb.phone in ('13600001111')"
    print(connect_mysql(sql_1))
    sql_2 = "delete from mb_member_register_log where phone in ('13600001111');"
    print(connect_mysql(sql_2))
